@file:Suppress("UNREACHABLE_CODE")

package com.eras.shoes.ui

import android.Manifest
import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.bluetooth.le.ScanResult
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.ActivityInfo
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.appcompat.widget.ListPopupWindow
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.eras.shoes.R
import com.eras.shoes.adapter.DeviceAdapter
import com.eras.shoes.contents.Api
import com.eras.shoes.contents.BleBean
import com.eras.shoes.contents.BleDataEx
import com.eras.shoes.contents.BluetoothDeviceWithRssi
import com.eras.shoes.contents.CalibrateBean
import com.eras.shoes.contents.Global
import com.eras.shoes.contents.MessageCallBack
import com.eras.shoes.contents.MessageEvent
import com.eras.shoes.contents.ProductSnPrefixCheck
import com.eras.shoes.contents.ShoesPressBack
import com.eras.shoes.contents.SmartShoesWebBean
import com.eras.shoes.contents.WeightData
import com.eras.shoes.databinding.ActivityCalibrateBinding
import com.eras.shoes.db.MacBlacklistManager
import com.eras.shoes.utils.BluetoothController
import com.eras.shoes.utils.BluetoothService
import com.eras.shoes.utils.DimensUtil
import com.eras.shoes.utils.FastClick
import com.eras.shoes.utils.LocationProvider
import com.eras.shoes.utils.LocationUtils
import com.eras.shoes.utils.OkHttpUtils
import com.eras.shoes.utils.OkHttpUtils.DataCallBack
import com.eras.shoes.utils.ShoeDataThread
import com.eras.shoes.utils.ToastUtils
import com.eras.shoes.utils.ZeroClearingManage
import com.eras.shoes.view.RxDialogSureCancel
import com.eras.shoes.view.popupdialog.PopupSheet
import com.eras.shoes.view.popupdialog.PopupSheetCallback
import com.google.gson.Gson
import okhttp3.Request
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONArray
import org.json.JSONObject
import java.io.IOException
import java.text.MessageFormat
import java.util.Arrays
import java.util.Objects
import kotlin.math.abs


class CalibrateActivity : ComponentActivity(), View.OnClickListener {
    private val TAG = "CalibrateActivity"
    private val PERMISSIONS_REQUEST_CODE = 101
    private val REQUIRED_PERMISSIONS = arrayOf(
        Manifest.permission.BLUETOOTH,
        Manifest.permission.BLUETOOTH_ADMIN,
        Manifest.permission.ACCESS_FINE_LOCATION
    )
    private val sharedPref by lazy {
        getSharedPreferences("login_prefs", Context.MODE_PRIVATE)
    }
    private lateinit var bluetoothService: BluetoothService

    private var broadcastReceiver: CalibrateActivity.BtTemperatureReceiver? = null
    // 蓝牙核心组件
    private val foundDevices = mutableListOf<BleBean>()
    private val bluetoothController = BluetoothController.getInstance()
    private val deviceList = mutableListOf<ScanResult>()
    private var connectDevice: BleBean = BleBean() //连接成功的设备
//    private var shoesName: String = ""
    private var SN: String = ""//序列号
    private var temperature: String = ""//温度值

    private val locationProvider by lazy { LocationProvider(this@CalibrateActivity) }
    var airPress: Double = 0.0
    val press = mutableListOf<CalibrateBean.press>()//压力和对应差值
    private lateinit var manager: MacBlacklistManager
    private var currentRssiThreshold = -40 // 默认功率阈值
    private var mProcDataThread: ShoeDataThread? = null
    private var shoesPress: Int = 0;

    //公司
    var companyCode: String = ""//ZH和XZ
    var companyName: String = ""
    var companyConfig: String = ""
    //训练仪
    var wordCode: String = ""//ZH和XZ
    var wordName: String = ""
    var wordConfig: String = ""
    //特征词
    var shoesCode: String = ""//ZH和XZ
    var shoesName: String = ""//蓝牙鞋
    var shoesConfig: String = ""
    //款型
    var serialCode: String = ""
    var serialName: String = ""
    var serialConfig: String = ""
    //颜色
    var colorCode: String = ""
    var colorlName: String = ""
    var colorConfig: String = ""
    //大小
    var sizeCode: String = ""
    var sizelName: String = ""
    var sizeConfig: String = ""
    //规格代码
    var specificationCode: String = ""
    var specificationName: String = ""
    var specificationConfig: String = ""

    var productSn: String = ""
    var productSnPrefix: String = ""
    // 在Activity中初始化适配器
    @SuppressLint("MissingPermission")
    private val adapter = DeviceAdapter { device ->
        connectToDevice(device)
    }

    // 添加设备超时管理
    private val deviceTimeoutMap = mutableMapOf<String, Long>() // 记录设备最后出现时间
    private val DEVICE_TIMEOUT = 10000L // 15秒超时（考虑间歇扫描）
    private val cleanupHandler = Handler(Looper.getMainLooper())
    private val cleanupRunnable = object : Runnable {
        override fun run() {
            removeTimeoutDevices()
            cleanupHandler.postDelayed(this, 2000) // 每2秒检查一次
        }
    }

    private lateinit var binding: ActivityCalibrateBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        binding = ActivityCalibrateBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.tvCalibrateUserName.setOnClickListener(this)
        binding.tvCalibrateRefresh.setOnClickListener(this)
        binding.tvCalibRssiIdFour.setOnClickListener(this)
        binding.tvCalibRssiIdFive.setOnClickListener(this)
        binding.tvCalibRssiIdSix.setOnClickListener(this)
        binding.tvCalibRssiIdSeven.setOnClickListener(this)
        binding.tvShoesPressTwo.setOnClickListener(this)
        binding.tvShoesZero.setOnClickListener(this)
        binding.tvShoesOne.setOnClickListener(this)
        binding.tvShoesTwo.setOnClickListener(this)
        binding.tvShoesThree.setOnClickListener(this)
        binding.tvShoesFive.setOnClickListener(this)
        binding.tvShoesSeven.setOnClickListener(this)
        binding.tvShoesTen.setOnClickListener(this)
        binding.btnStartVerify.setOnClickListener(this)

        binding.btnShoesSaveCalibrate.setOnClickListener(this)
        binding.btnShoesSaveCalibrate.setBackgroundResource(R.drawable.bg_grey_btn)
        binding.btnShoesSaveCalibrate.isEnabled = false
        binding.btnShoesFailCalibrate.setOnClickListener(this)
        binding.btnShoesFailCalibrate.setBackgroundResource(R.drawable.bg_grey_btn)
        binding.btnShoesFailCalibrate.isEnabled = false
        manager = MacBlacklistManager(this@CalibrateActivity)
//        getDate()

        binding.tvShoesZero.setBackgroundResource(R.drawable.bg_grey_btn)
        binding.tvShoesZero.isEnabled = false
        binding.tvShoesOne.setBackgroundResource(R.drawable.bg_grey_btn)
        binding.tvShoesOne.isEnabled = false
        binding.tvShoesTwo.setBackgroundResource(R.drawable.bg_grey_btn)
        binding.tvShoesTwo.isEnabled = false
        binding.tvShoesThree.setBackgroundResource(R.drawable.bg_grey_btn)
        binding.tvShoesThree.isEnabled = false
        binding.tvShoesFive.setBackgroundResource(R.drawable.bg_grey_btn)
        binding.tvShoesFive.isEnabled = false
        binding.tvShoesSeven.setBackgroundResource(R.drawable.bg_grey_btn)
        binding.tvShoesSeven.isEnabled = false
        binding.tvShoesTen.setBackgroundResource(R.drawable.bg_grey_btn)
        binding.tvShoesTen.isEnabled = false
        binding.btnStartVerify.setBackgroundResource(R.drawable.bg_grey_btn)
        binding.btnStartVerify.isEnabled = false
        binding.tvVerifyWeight.setOnClickListener(this)
//        mProcDataThread.mCalibrateActivity = this@CalibrateActivity
//        mProcDataThread.StartThread()

        // 获取drawable对象
        val drawable = resources.getDrawable(R.drawable.ic_down_black)
       // 设置drawable的bounds
        drawable.setBounds(0, 0, 40, 30) // 宽度和高度设为50dp
        // 设置到TextView
        binding.tvVerifyWeight.setCompoundDrawables(null, null, drawable, null)
    }

    override fun onStart() {
        super.onStart()
        val savedUsername = sharedPref.getString("username", "")
        binding.tvCalibrateUserName.text = savedUsername

        bluetoothService = BluetoothService(this)

        checkPermissions()

        binding.rvCalibrateBt.apply {
            layoutManager = LinearLayoutManager(this@CalibrateActivity)
            adapter = this@CalibrateActivity.adapter
            addItemDecoration(DividerItemDecoration(this@CalibrateActivity, LinearLayoutManager.VERTICAL))
        }

        bluetoothController.initBle(this)
        // 检查权限
        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(REQUIRED_PERMISSIONS, PERMISSIONS_REQUEST_CODE)
        } else {
            initBtState()
        }
        getDate()
        getCalibConfig()
        if (Global.lng == 0.toDouble() && Global.lat == 0.toDouble()) {
            val message = Message()
            message.obj = "获取定位失败，正在重新获取"
            message.arg1 = 11
            handler.sendMessage(message)
//            checkLocation()
            if (checkPermission()) {
                startNetworkLocation()
            }
        }
    }

//    private fun getDate() {

//        // 接收基本数据类型
//        companyCode = intent.getStringExtra("companyCode").toString()
//        companyName = intent.getStringExtra("companyName").toString()
//        companyConfig = intent.getStringExtra("companyConfig").toString()
//
//        wordCode = intent.getStringExtra("wordCode").toString()
//        wordName = intent.getStringExtra("wordName").toString()
//        shoesConfig = intent.getStringExtra("shoesConfig").toString()
//
//        shoesCode = intent.getStringExtra("shoesCode").toString()
//        shoesName = intent.getStringExtra("shoesName").toString()
//        shoesConfig = intent.getStringExtra("shoesConfig").toString()
//
//        serialCode = intent.getStringExtra("serialCode").toString()
//        serialName = intent.getStringExtra("serialName").toString()
//        serialConfig = intent.getStringExtra("serialConfig").toString()
//
//        colorCode = intent.getStringExtra("colorCode").toString()
//        colorlName = intent.getStringExtra("colorlName").toString()
//        colorConfig = intent.getStringExtra("colorConfig").toString()
//
//        sizeCode = intent.getStringExtra("sizeCode").toString()
//        sizelName = intent.getStringExtra("sizelName").toString()
//        sizeConfig = intent.getStringExtra("sizeConfig").toString()
//
//        specificationCode = intent.getStringExtra("specificationCode").toString()
//        specificationName = intent.getStringExtra("specificationName").toString()
//        specificationConfig = intent.getStringExtra("specificationConfig").toString()

//        footType = intent.getStringExtra("footType").toString()
//        if (Global.footName.equals("左脚")) {
//            binding.tvWriteFootTypeLeft.setTextColor(ContextCompat.getColor(this@MainBoardActivity, R.color.white))
//            binding.tvWriteFootTypeLeft.setBackgroundResource(R.drawable.bg_orange_btn)
//
//            binding.tvWriteFootTypeRight.setTextColor(ContextCompat.getColor(this@MainBoardActivity, R.color.black))
//            binding.tvWriteFootTypeRight.setBackgroundResource(R.drawable.bg_black_frame_btn)
//        } else if (Global.footName.equals("右脚")) {
//            binding.tvWriteFootTypeLeft.setTextColor(ContextCompat.getColor(this@MainBoardActivity, R.color.black))
//            binding.tvWriteFootTypeLeft.setBackgroundResource(R.drawable.bg_black_frame_btn)
//
//            binding.tvWriteFootTypeRight.setTextColor(ContextCompat.getColor(this@MainBoardActivity, R.color.white))
//            binding.tvWriteFootTypeRight.setBackgroundResource(R.drawable.bg_orange_btn)
//        }

//        setConfigDate()

//    }

    /**
     * 初始化蓝牙状态广播监听
     */
    private fun initBtState() {
        if (bluetoothController.isBleOpen) {
            bluetoothController.startScanBle()
        } else {
            bluetoothController.initBle(this)
        }
    }

    private fun checkPermissions() {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            requestPermissions(arrayOf(
                Manifest.permission.BLUETOOTH_SCAN,
                Manifest.permission.BLUETOOTH_CONNECT,
                Manifest.permission.ACCESS_FINE_LOCATION
            ), 1)
        }
    }

    @SuppressLint("MissingPermission", "NotifyDataSetChanged")
    private fun connectToDevice(device: BleBean) {
        if(Global.connectState == 1) {
            ToastUtils().show(this@CalibrateActivity, "有设备正在连接中...")
            return
        }
        if (BluetoothController.macAddress == null) {
            device.connectState = 0
            Global.connectType = 0
            Global.address = device.address
            adapter.notifyDataSetChanged()
            bluetoothController.connect(device.address)
            return
        }
        if (BluetoothController.macAddress != null && BluetoothController.macAddress.equals(device.address)) {
            ToastUtils().show(this@CalibrateActivity, "该设备已连接")
            return
        }
        if (BluetoothController.macAddress != null) {
            bluetoothController.closeBuletooth(BluetoothController.macAddress)
            reSetAllPress()
            device.connectState = 0
            Global.connectType = 0
            Global.address = device.address
            adapter.notifyDataSetChanged()
            bluetoothController.connect(device.address)
        }
        Log.e("CalibrateActivity", "正在连接: ${device.name}")
    }

    // 获取蓝牙适配器
    private val bluetoothAdapter: BluetoothAdapter? by lazy {
        val bluetoothManager = getSystemService(BLUETOOTH_SERVICE) as BluetoothManager
        bluetoothManager.adapter
    }
    private fun updateDeviceList(device: BluetoothDeviceWithRssi) {
        val existingIndex = foundDevices.indexOfFirst {
            it.address == device.bean.address
        }
        if (existingIndex >= 0) {
            foundDevices[existingIndex] = device.bean
        } else {
            foundDevices.add(device.bean)
        }
        foundDevices.sortByDescending { device.bean.rssi } // 按value降序排序
        adapter.submitList(foundDevices.toList())
    }


    // 处理主线程事件（默认模式）
    @SuppressLint("NotifyDataSetChanged")
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: MessageEvent<*>) {
        var bleBeans: BleBean
        when (event.getAction()) {
            MessageEvent.ACTION_GATT_CONNECTED -> {
                Global.connectState = 2
                Global.isConnected = true
                bleBeans = event.data as BleBean
                Global.connectType = 1
                for (i in 0 until foundDevices.size) {
                    val bleBean: BleBean = foundDevices.get(i)
                    if (bleBean.address.equals(bleBeans.address)) {
                        bleBean.connectState = 1
                        bleBeans = bleBean
                    }
                }
                adapter.notifyDataSetChanged()
                connectSuccess(bleBeans)
            }

            MessageEvent.ACTION_GATT_DISCONNECTED -> {
                Global.connectState = 0
                val address = event.data as String
                Global.isConnected = false
                Global.connectType = -1
                BluetoothController.macAddress = null
                Global.address = null
                for (i in 0 until foundDevices.size) {
                    val bleBean: BleBean = foundDevices.get(i)
                    if (bleBean.address.equals(address)) {
                        bleBean.connectState = -1
                    }
                }
                adapter.notifyDataSetChanged()
            }

            MessageEvent.BLE_SCAN_RESULT -> {
                // 添加蓝牙
                addBluetooth(event.data as ScanResult)
            }

            MessageEvent.EVENT_DEVICE_COLL_BACK -> {
                Log.i("MainBoardActivity", "EVENT_DEVICE_COLL_BACK :" + event.data)
                val strRecvTxt = java.lang.String.valueOf(event.data)
                if (strRecvTxt.length > 1) {
                    val gson: Gson = Gson()
                    val messageCallBack: MessageCallBack =
                        gson.fromJson(strRecvTxt, MessageCallBack::class.java)
                    val message = Message()
                    message.obj = messageCallBack.msg
                    message.arg1 = 1
//                    handlerSetText.sendMessage(message)
                }
            }
            MessageEvent.SMART_SHOES_BLUETOOTH_DATA -> {
                val ldata: SmartShoesWebBean = event.data as SmartShoesWebBean
                zcm.setLeftData(ldata.getBulDate())
                mProcDataThread?.AddShoesData(ldata)

            }
            MessageEvent.SMART_SHOES_PRESS_DATA_BACK -> {
                val pressData: ShoesPressBack = event.data as ShoesPressBack
                setDataToView(pressData);

            }

        }
    }

    @SuppressLint("MissingPermission")
    private fun addBluetooth(result: ScanResult) {
        if (manager.isBlacklisted(result.device.address)) {
            return
        }
        if (currentRssiThreshold >= result.rssi) {
            return
        }

        val type = if (result.device.name.contains("LEFT") || result.device.name.contains("左")) {
            0
        } else if (result.device.name.contains("RIGHT") || result.device.name.contains("右")) {
            1
        } else {
            2
        }

        if (type ==2){
            return
        }
        Log.i(TAG, "onScanResult: type$type")
        // 更新设备最后出现时间
        deviceTimeoutMap[result.device.address] = System.currentTimeMillis()

        this.runOnUiThread(Runnable {

            // 先移除超时设备
            removeTimeoutDevices()

            if (!deviceList.any { it.device.address == result.device.address }) {
                deviceList.add(result)
                val bytes = result.scanRecord!!.bytes
                var serialNumber = BleDataEx.getStringValue(bytes, 17, 10)
                // 序列号过滤逻辑  YK257J051��, 00000000����, YK124B2345, YK257J051��  00000000����
                if (serialNumber != null) {
                    // 如果包含"00000000"则丢弃
                    if (serialNumber.contains("00000000")) {
                        serialNumber = "00000000"
                    } else {
                        // 找到第一个非字母数字字符的位置
                        var invalidCharIndex = -1
                        for (i in 0 until serialNumber.length) {
                            val c = serialNumber[i]
                            if (!Character.isLetterOrDigit(c)) {
                                invalidCharIndex = i
                                break
                            }
                        }

                        // 如果有乱码，截取有效部分
                        if (invalidCharIndex != -1) {
                            serialNumber =
                                serialNumber.substring(0, invalidCharIndex)
                        }
                    }
                }

                val bean = BleBean(result.device.name, result.device.address, -1, result.rssi, serialNumber ,type)
                updateDeviceList(BluetoothDeviceWithRssi(bean, result.rssi))
            }
        })
    }

    @SuppressLint("MissingPermission", "NotifyDataSetChanged")
    private fun connectSuccess(data: BleBean) {
        connectDevice = data
        SN = data.serialNumber
        this.runOnUiThread(Runnable {
            val name = data.name
            shoesName = name
//            val address = data.address
//            BluetoothController.macAddress = address

            when (data.type) {
                2 -> showType2Dialog()
                0 -> handleType0()
                1 -> handleType1()
                else -> Log.w(TAG, "Unknown device type: ${data.type}")
            }
            Log.e(TAG, "calibCheck:"+data.type+","+Global.footCode+","+productSnPrefix)

        })
    }

    private fun showType2Dialog() {
        RxDialogSureCancel(this@CalibrateActivity).apply {
            setSureListener {
                dismiss()
                disConnect() // 断开连接
                finish()    // 结束当前Activity，返回上一页
                 }
            show()
        }
    }


    private fun showCalibCheckDialog(message: String) {
        RxDialogSureCancel(this@CalibrateActivity).apply {
            contentView.text = message
            setSureListener {
                dismiss()
//                disConnect() // 断开连接
//                finish()    // 结束当前Activity，返回上一页
            }
            show()
        }
    }

    private fun handleType0() {
        Global.footCode = "Z"
        updateProductSnPrefix()
    }

    private fun handleType1() {
        Global.footCode = "Y"
        updateProductSnPrefix()
    }

    private fun updateProductSnPrefix() {
        productSnPrefix = companyCode + shoesCode + wordCode + serialCode +
                specificationCode + Global.footCode + sizeCode +
                colorCode + Global.colorConfig
        calibCheck()
    }

    private fun setEnableClick() {
        runOnUiThread {
            binding.tvShoesZero.setBackgroundResource(R.drawable.bg_orange_btn)
            binding.tvShoesZero.isEnabled = true
            binding.tvShoesOne.setBackgroundResource(R.drawable.bg_orange_btn)
            binding.tvShoesOne.isEnabled = true
            binding.tvShoesTwo.setBackgroundResource(R.drawable.bg_orange_btn)
            binding.tvShoesTwo.isEnabled = true
            binding.tvShoesThree.setBackgroundResource(R.drawable.bg_orange_btn)
            binding.tvShoesThree.isEnabled = true
            binding.tvShoesFive.setBackgroundResource(R.drawable.bg_orange_btn)
            binding.tvShoesFive.isEnabled = true
            binding.tvShoesSeven.setBackgroundResource(R.drawable.bg_orange_btn)
            binding.tvShoesSeven.isEnabled = true
            binding.tvShoesTen.setBackgroundResource(R.drawable.bg_orange_btn)
            binding.tvShoesTen.isEnabled = true
        }
    }


    override fun onResume() {
        super.onResume()
        // 启动设备清理任务
        cleanupHandler.postDelayed(cleanupRunnable, 2000)
//        if (binding.tvSerialNumber.text.equals("")) {
//            binding.llWrite.visibility = View.GONE
//        }
        if (!EventBus.getDefault().isRegistered(this)) { //加上判断
            EventBus.getDefault().register(this)
        }
        broadcastReceiver = CalibrateActivity.BtTemperatureReceiver()
        val intentFilter = IntentFilter()
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED)
        registerReceiver(broadcastReceiver, intentFilter)
    }

    override fun onPause() {
        // 停止设备清理任务
        cleanupHandler.removeCallbacks(cleanupRunnable)
        super.onPause()
        EventBus.getDefault().unregister(this)
        unregisterReceiver(broadcastReceiver) //注销广播接收器
    }

    override fun onDestroy() {
        super.onDestroy()
        // 停止清理任务
        cleanupHandler.removeCallbacks(cleanupRunnable)
        deviceTimeoutMap.clear()

        foundDevices.clear()
        deviceList.clear()
        adapter.submitList(emptyList())
        bluetoothController.stopScanBle()

        if (BluetoothController.macAddress != null) {
            bluetoothController.closeBuletooth(BluetoothController.macAddress)
        }


    }

    override fun onBackPressed() {
        super.onBackPressed()
        disConnect()
        finish()
    }

    /**
     * 蓝牙状态广播回调
     */
    internal class BtTemperatureReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            //注意!这里是先拿action 等于 BluetoothAdapter.ACTION_STATE_CHANGED 在解析intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0)
            if (BluetoothAdapter.ACTION_STATE_CHANGED == Objects.requireNonNull<String?>(action)) {
                val blState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0)
                when (blState) {
                    BluetoothAdapter.STATE_TURNING_ON -> {
                    }
                    BluetoothAdapter.STATE_ON ->
//                        ToastUtils.show(ConnectDeviceActivity.this, "蓝牙开启成功");
//                        Toast.makeText(ConnectDeviceActivity.this,"蓝牙开启成功",Toast.LENGTH_SHORT).show();
                    {
                        BluetoothController.getInstance().startScanBle()
                    }

                    BluetoothAdapter.STATE_TURNING_OFF -> //                        ToastUtils.show(ConnectDeviceActivity.this, "蓝牙正在关闭中……，请稍等");
//                        Toast.makeText(ConnectDeviceActivity.this,"蓝牙正在关闭中……，请稍等",Toast.LENGTH_SHORT).show();

                    {

                    }
                    BluetoothAdapter.STATE_OFF -> {
                        //                        ToastUtils.show(ConnectDeviceActivity.this, "蓝牙已关闭");
//                        Toast.makeText(ConnectDeviceActivity.this,"蓝牙已关闭",Toast.LENGTH_SHORT).show();
                    }

                    BluetoothAdapter.ERROR -> {

                    }

                    else -> {}
                }
            }
        }
    }

    var tag = 5
    private fun upCalibrate(mac: String, SN: String , productSnPrefix:String , temperature: String) {
        val user = CalibrateBean("", "",  "",  "" ,ArrayList())
        user.mac = mac
        user.shortProductSn = SN
        user.temperature = temperature
        user.productSnPrefix = productSnPrefix
        user.items = press
        val data = Gson().toJson(user)
        OkHttpUtils.postJsonAsync(this@CalibrateActivity, Api.calibrateSave, data, object : OkHttpUtils.DataCallBack {
            override fun requestFailure(request: Request, e: IOException) {
                Log.e("CalibrateActivity", "上传失败")
                if(tag-- > 0) {
                    upCalibrate(mac, SN , productSnPrefix,temperature)
                } else {
                    binding.pbLoadingSave.visibility = View.GONE
                    mProcDataThread?.StopThread()
                    disConnect()
                    bluetoothController.startScanBle()
                    ToastUtils().show(this@CalibrateActivity, "上传失败，请检查网络是否异常")
                }
            }

            @Throws(Exception::class)
            override fun requestSuccess(result: String) {
                binding.pbLoadingSave.visibility = View.GONE
                val toJsonObj = JSONObject(result)
                Log.e("CalibrateActivity", "上传返回"+toJsonObj)
                val code = toJsonObj.getInt("code")
                tag = 0
                if (code == 0) {
                    manager.addToBlacklist(mac)
                    mProcDataThread?.StopThread()
                    disConnect()
                    bluetoothController.startScanBle()
                    val messages = toJsonObj["message"] as String
                    val message = Message()
                    message.obj = messages
                    message.arg1 = 11
                    handler.sendMessage(message)
                } else {
                    val messages = toJsonObj["message"] as String
                    val message = Message()
                    message.obj = messages
                    message.arg1 = 11
                    handler.sendMessage(message)
                }
            }
        })
    }

    @SuppressLint("ResourceAsColor")
    override fun onClick(p0: View?) {

        when (p0?.id){
            R.id.tv_calibrate_userName -> {
                disConnect()
                finish()
            }
            R.id.tv_calibrate_refresh -> {
                if (FastClick.isFastClick()) {
                    ToastUtils().show(this@CalibrateActivity, "请不要连续多次点击")
                    return
                }
                // 清空超时记录，强制刷新
                deviceTimeoutMap.clear()
                foundDevices.clear()
                deviceList.clear()
//                adapter.submitList(emptyList())
                if (BluetoothController.macAddress != null){
                    foundDevices.add(connectDevice)
                    // 更新当前连接设备的超时时间
                    deviceTimeoutMap[connectDevice.address] = System.currentTimeMillis()
                }
                adapter.submitList(foundDevices.toList())
                bluetoothController.startScanBle()
            }
            R.id.tv_calib_rssi_id_four -> {
                reSetRissbg("-40")
                binding.tvCalibRssiIdFour.setBackgroundResource(R.drawable.bg_orange_btn)
                binding.tvCalibRssiIdFour.setTextColor(ContextCompat.getColor(this@CalibrateActivity, R.color.white))
//                val arrayBlueRssiId: Array<String> = resources.getStringArray(R.array.blue_rssi_id)
//                selectBlueRssiId(binding.tvCalibRssiId, arrayBlueRssiId)
            }
            R.id.tv_calib_rssi_id_five -> {
                reSetRissbg("-50")
                binding.tvCalibRssiIdFive.setBackgroundResource(R.drawable.bg_orange_btn)
                binding.tvCalibRssiIdFive.setTextColor(ContextCompat.getColor(this@CalibrateActivity, R.color.white))
            }
            R.id.tv_calib_rssi_id_six -> {
                reSetRissbg("-60")
                binding.tvCalibRssiIdSix.setBackgroundResource(R.drawable.bg_orange_btn)
                binding.tvCalibRssiIdSix.setTextColor(ContextCompat.getColor(this@CalibrateActivity, R.color.white))
            }
            R.id.tv_calib_rssi_id_seven -> {
                reSetRissbg("-70")
                binding.tvCalibRssiIdSeven.setBackgroundResource(R.drawable.bg_orange_btn)
                binding.tvCalibRssiIdSeven.setTextColor(ContextCompat.getColor(this@CalibrateActivity, R.color.white))
            }
            R.id.tv_shoes_zero -> {
                if (FastClick.isFastClick()) {
                    ToastUtils().show(this@CalibrateActivity, "请不要连续多次点击")
                    return
                }
                if (checkConnected()){
                    return
                }
                Thread{
                    mondifyFlowStatus(0, binding.tvShoesZero, binding.tvShoesPressZero)
                }.start()
            }
            R.id.tv_shoes_one -> {
                if (FastClick.isFastClick()) {
                    ToastUtils().show(this@CalibrateActivity, "请不要连续多次点击")
                    return
                }
                if (checkConnected()){
                    return
                }
                Thread{
                    mondifyFlowStatus(1, binding.tvShoesOne, binding.tvShoesPressOne)
                }.start()

            }
            R.id.tv_shoes_two -> {
                if (FastClick.isFastClick()) {
                    ToastUtils().show(this@CalibrateActivity, "请不要连续多次点击")
                    return
                }
                if (checkConnected()){
                    return
                }
                Thread{
                    mondifyFlowStatus(2, binding.tvShoesTwo, binding.tvShoesPressTwo)
                }.start()

            }
            R.id.tv_shoes_three -> {
                if (FastClick.isFastClick()) {
                    ToastUtils().show(this@CalibrateActivity, "请不要连续多次点击")
                    return
                }
                if (checkConnected()){
                    return
                }
                Thread{
                    mondifyFlowStatus(3,binding.tvShoesThree, binding.tvShoesPressThree)
                }.start()

            }
            R.id.tv_shoes_five -> {
                if (FastClick.isFastClick()) {
                    ToastUtils().show(this@CalibrateActivity, "请不要连续多次点击")
                    return
                }
                if (checkConnected()){
                    return
                }
                Thread{
                    mondifyFlowStatus(5, binding.tvShoesFive, binding.tvShoesPressFive)
                }.start()

            }
            R.id.tv_shoes_seven -> {
                if (FastClick.isFastClick()) {
                    ToastUtils().show(this@CalibrateActivity, "请不要连续多次点击")
                    return
                }
                if (checkConnected()){
                    return
                }
                Thread{
                    mondifyFlowStatus(7, binding.tvShoesSeven, binding.tvShoesPressSeven)
                }.start()

            }
            R.id.tv_shoes_ten -> {
                if (FastClick.isFastClick()) {
                    ToastUtils().show(this@CalibrateActivity, "请不要连续多次点击")
                    return
                }
                if (checkConnected()){
                    return
                }
                Thread{
                    mondifyFlowStatus(10, binding.tvShoesTen, binding.tvShoesPressTen)
                }.start()

            }
            R.id.btn_start_verify -> {
                if (FastClick.isFastClick()) {
                    ToastUtils().show(this@CalibrateActivity, "请不要连续多次点击")
                    return
                }
                if (press.size < 7) {
                    val message = Message()
                    message.obj = "请完成所有定标"
                    message.arg1 = 11
                    handler.sendMessage(message)
                    return
                }
                if (shoesPress == 0) {
                    ToastUtils().show(this@CalibrateActivity, "请选择验证负重值")
                } else {
                    mProcDataThread = ShoeDataThread(this@CalibrateActivity, press)
                    mProcDataThread!!.StartThread()
                }

            }
            R.id.btn_shoes_save_calibrate -> {
                if(avoidFastClick(2000)) {
                    if (checkConnected()){
                        return
                    }
                    binding.pbLoadingSave.visibility = View.VISIBLE
                    upCalibrate(
                        BluetoothController.macAddress, SN, productSnPrefix,temperature
                    )
                }

            }
            R.id.btn_shoes_fail_calibrate -> {
                if (FastClick.isFastClick()) {
                    ToastUtils().show(this@CalibrateActivity, "请不要连续多次点击")
                    return
                }
                mProcDataThread?.StopThread()
                Press0 = 0.0
                reSetValue()
//                reSetAllPress()

            }
            R.id.tv_verify_weight -> {
                if (FastClick.isFastClick()) {
                    ToastUtils().show(this@CalibrateActivity, "请不要连续多次点击")
                    return
                }
                val arrayVerifyWeight: Array<String> = resources.getStringArray(R.array.verify_weight)
                selectBlueRssiId(binding.tvVerifyWeight, arrayVerifyWeight)
//                if (shoesPress == 0) {
//                    ToastUtils().show(this@CalibrateActivity, "请选择验证负重值")
//                } else {
//                    val arrayVerifyWeight: Array<String> = resources.getStringArray(R.array.verify_weight)
//                    selectBlueRssiId(binding.tvVerifyWeight, arrayVerifyWeight)
//                }

            }
        }
    }


    var zcm: ZeroClearingManage = ZeroClearingManage()
    var count = 1
    var Press0: Double = 0.0
    private fun mondifyFlowStatus(tag: Int, view0: TextView, view1: TextView) {
        if (!Global.isConnected) {
            val message = Message()
            message.obj = "请先连接蓝牙鞋"
            message.arg1 = 11
            handler.sendMessage(message)
            return
        }
        val data = zcm.getLeftData()
        val leftData = data.pressure
        val temperatureF = data.temperature
        Log.i("CalibrateActivity", "mondifyFlowStatus l: $leftData, temperature: $temperatureF")
        temperature = ZeroClearingManage.formatWithStringFormatFloat(temperatureF)
        if (leftData > 0) {
                count = 1
                if (tag == 0) {
//                    if (Press0 == 0.0) {
//                        setEnableClick()
//                    }
                    Press0 = leftData
                    Global.P0 = Press0

                }
                runOnUiThread {
                    view1.text = ZeroClearingManage.formatWithStringFormat(leftData)
                    view0.setBackgroundResource(R.drawable.bg_green_btn)
                    //                    android.util.Log.i(TAG,"蓝牙状态输出:设备已连接,设置MTU[183],name[" + device.getName() + "]address[" + device.getAddress() + "]");
//                    //handle消息
                    val message = Message()
                    message.obj = leftData
                    message.arg1 = tag
                    handler.sendMessage(message)
                }
        } else {
            count--
            if (count >= 0) {
                mondifyFlowStatus(tag, view0, view1)
            } else {
                count = 1
                val message = Message()
                message.obj = "获取压力失败"
                message.arg1 = 11
                handler.sendMessage(message)
            }
        }
    }
    fun objectToDouble(obj: Any?): Double? {
        return when (obj) {
            is Double -> obj
            is Number -> obj.toDouble()
            is String -> obj.toDoubleOrNull()
            else -> null
        }
    }
    @SuppressLint("HandlerLeak")
    var handler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            val press = msg.obj
            val type = msg.arg1
            when (type) {
                0 -> {
                    objectToDouble(press)?.let {
                        binding.tvShoesAirPressZeroValue.text = getShoesAirPress("0", it, Global.P0, binding.tvShoesZero)
                        checkGetAirPress(
                            "0", binding.tvAirPressZeroValue,
                            binding.tvShoesAirPressZeroValue,
                            binding.pbLoadingZero, it
                        )
                    }
                }
                1 -> {
                    objectToDouble(press)?.let {
                        binding.tvShoesAirPressValueOne.text = getShoesAirPress("10", it, Global.P0, binding.tvShoesOne)
                        checkGetAirPress("10", binding.tvAirPressValueOne,
                            binding.tvShoesAirPressValueOne,
                            binding.pbLoadingZero, it
                        )
                    }
                }
                2 -> {
                    objectToDouble(press)?.let {
                        binding.tvShoesAirPressValueTwo.text = getShoesAirPress("20", it, Global.P0, binding.tvShoesTwo)
                        checkGetAirPress("20", binding.tvAirPressValueTwo,
                            binding.tvShoesAirPressValueTwo,
                            binding.pbLoadingZero, it
                        )
                    }
                }
                3 -> {
                    objectToDouble(press)?.let {
                        binding.tvShoesAirPressValueThree.text = getShoesAirPress("30", it, Global.P0, binding.tvShoesThree)
                        checkGetAirPress("30", binding.tvAirPressValueThree,
                            binding.tvShoesAirPressValueThree,
                            binding.pbLoadingZero, it
                        )
                    }
                }
                5 -> {
                    objectToDouble(press)?.let {
                        binding.tvShoesAirPressValueFive.text = getShoesAirPress("50", it, Global.P0, binding.tvShoesFive)
                        checkGetAirPress("50", binding.tvAirPressValueFive,
                            binding.tvShoesAirPressValueFive,
                            binding.pbLoadingZero, it
                        )
                    }
                }
                7 -> {
                    objectToDouble(press)?.let {
                        binding.tvShoesAirPressValueSeven.text = getShoesAirPress("70", it, Global.P0, binding.tvShoesSeven)
                        checkGetAirPress("70", binding.tvAirPressValueSeven,
                            binding.tvShoesAirPressValueSeven,
                            binding.pbLoadingZero, it
                        )
                    }
                }
                10 -> {
                    objectToDouble(press)?.let {
                        binding.tvShoesAirPressValueTen.text = getShoesAirPress("100", it, Global.P0, binding.tvShoesTen)
                        checkGetAirPress("100", binding.tvAirPressValueTen,
                            binding.tvShoesAirPressValueTen,
                            binding.pbLoadingZero, it
                        )
                    }
                }
                11 -> {
                    ToastUtils().show(this@CalibrateActivity, press.toString())
                }
            }
        }
    }

    private fun checkConnected(): Boolean {
        if (BluetoothController.macAddress == null) {
            val message = Message()
            message.obj = "请先连接蓝牙鞋"
            message.arg1 = 11
            handler.sendMessage(message)
            return true
        }
        return false
    }


    private fun checkGetAirPress(pre: String, viewp: TextView, views: TextView, viewb: ProgressBar, shoesPress: Double) {
        if (Global.lng == 0.toDouble() && Global.lat == 0.toDouble()) {
//            val message = Message()
//            message.obj = "获取定位失败，正在重新获取"
//            message.arg1 = 11
//            handler.sendMessage(message)
//            checkLocation()
            if (checkPermission()) {
                startNetworkLocation()
            }
        } else {
            viewb.visibility = View.VISIBLE
            getLoaclPress(
                pre,
                Global.lng,
                Global.lat,
                viewp,
                views,
                viewb,
                shoesPress
            )
        }
    }

    private fun selectBlueRssiId(view: TextView, arrays: Array<String>) {
        val popupSheet: PopupSheet
        val arrayList = Arrays.asList(*arrays)
        popupSheet =
            PopupSheet(this@CalibrateActivity, view, arrayList, object : PopupSheetCallback {
                override fun setupItemView(position: Int): View {
                    val itemV: View =
                        LayoutInflater.from(this@CalibrateActivity)
                            .inflate(R.layout.item_surgery_name, null)
                    val titleTV = itemV.findViewById<TextView>(R.id.tv_surgery_name)
                    titleTV.text = MessageFormat.format("{0}", arrayList[position])
                    return itemV
                }

                override fun itemClicked(popupWindow: ListPopupWindow, position: Int) {
                    popupWindow.dismiss()
                    shoesPress = arrayList[position].toInt()
                    view.text = arrayList[position] + "Kg"

                }
            }, DimensUtil.dp2px(this@CalibrateActivity, 140F))
        popupSheet.show()
    }

    private fun checkLocation() {
        // 检查并请求位置权限
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                100
            )
        } else {
            getLocation()
        }
    }
    private fun getLocation() {
        LocationUtils.getCurrentLocation(this@CalibrateActivity) { lat, lng ->
            // 在这里处理获取到的经纬度
            println("纬度: $lat, 经度: $lng")
            Global.lat = lat
            Global.lng = lng
            Log.e("CalibrateActivity", "纬度: "+lat+", 经度: "+lng)
            val message = Message()
            message.obj = "以获取到经纬度,重新点击定标获取大气压"
            message.arg1 = 11
            handler.sendMessage(message)
        }
    }

//    override fun onRequestPermissionsResult(
//        requestCode: Int,
//        permissions: Array<out String>,
//        grantResults: IntArray
//    ) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
//        if (requestCode == 100 && grantResults.isNotEmpty() &&
//            grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//            getLocation()
//        }
//    }

    /**
     * 获取当前气压
     */
    private fun getLoaclPress(pre: String, lon: Double, lat: Double, viewp: TextView, views: TextView, viewb: ProgressBar, shoesPress: Double) {
        Log.e("CalibrateActivity", "?longitude=" + lon + "&latitude=" + lat)
        OkHttpUtils.getAsyncToken(this@CalibrateActivity, Api.loaclPress + "?longitude=" + lon + "&latitude=" + lat,
            false,
            object : OkHttpUtils.DataCallBack {
                override fun requestFailure(request: Request?, e: IOException?) {
                    if (count-- <= 0) {
                        viewb.visibility = View.INVISIBLE
                        val message = Message()
                        message.obj = "获取当前气压失败，请退出重进"
                        message.arg1 = 11
                        handler.sendMessage(message)
                    } else {
                        getLoaclPress(pre, lon, lat, viewp, views, viewb, shoesPress)
                    }
                }

                @Throws(java.lang.Exception::class)
                override fun requestSuccess(result: String?) {
                    viewb.visibility = View.INVISIBLE
                    // todo 上传评估记录完成
                    val jsonObject = com.alibaba.fastjson.JSONObject.parseObject(result)
                    val code = jsonObject["code"] as Int
                    Log.e("CalibrateActivity", "code:"+code)
                    if (code == 0) {
                        val press = jsonObject.getDouble("data")
                        airPress = press
                        Global.airPress = press
                        runOnUiThread {
                            viewp.text = ZeroClearingManage.formatWithStringFormat(airPress)
//                            views.text = getShoesAirPress(pre, shoesPress, airPress)
                        }

                        Log.e("CalibrateActivity", "data:"+press)
                    } else {
                        val messages = jsonObject["msg"] as String?
                        val message = Message()
                        message.obj = messages
                        message.arg1 = 11
                        handler.sendMessage(message)
                    }
                }
            })
    }

    private fun getShoesAirPress(pr: String, num1: Double, num2: Double, view: TextView): String {
        val iterator = press.iterator()
        while (iterator.hasNext()) {
            val item = iterator.next()
            if (item.pressure == pr) {
                Log.e("CalibrateActivity", "pr="+pr)
                iterator.remove() // 安全删除
            }
        }
        val result = num1 - num2
        if(checkIn(result, pr.toInt())) {
            ToastUtils().show(this@CalibrateActivity, "定标压力差不在正常范围，请重新定标")
            view.setBackgroundResource(R.drawable.btn_red_bg)
            return ""
        }
//        view.setBackgroundResource(R.drawable.bg_orange_btn)
        var pre = CalibrateBean.press(pr, result.toString())
        press.add(pre)

        Log.e("CalibrateActivity", "pressSize="+press.size)
        if (press.size == 7) {
            binding.btnStartVerify.setBackgroundResource(R.drawable.bg_orange_btn)
            binding.btnStartVerify.isEnabled = true
        } else {
            binding.btnStartVerify.setBackgroundResource(R.drawable.bg_grey_btn)
            binding.btnStartVerify.isEnabled = false
        }

        return ZeroClearingManage.formatWithStringFormat(result)
    }

    private fun reSetAllPress() {
        runOnUiThread {
            binding.tvShoesPressZero.text = ""
            binding.tvAirPressZeroValue.text = ""
            binding.tvShoesAirPressZeroValue.text = ""
            binding.tvShoesPressOne.text = ""
            binding.tvAirPressValueOne.text = ""
            binding.tvShoesAirPressValueOne.text = ""
            binding.tvShoesPressTwo.text = ""
            binding.tvAirPressValueTwo.text = ""
            binding.tvShoesAirPressValueTwo.text = ""
            binding.tvShoesPressThree.text = ""
            binding.tvAirPressValueThree.text = ""
            binding.tvShoesAirPressValueThree.text = ""
            binding.tvShoesPressFive.text = ""
            binding.tvAirPressValueFive.text = ""
            binding.tvShoesAirPressValueFive.text = ""
            binding.tvShoesPressSeven.text = ""
            binding.tvAirPressValueSeven.text = ""
            binding.tvShoesAirPressValueSeven.text = ""
            binding.tvShoesPressTen.text = ""
            binding.tvAirPressValueTen.text = ""
            binding.tvShoesAirPressValueTen.text = ""
            binding.tvShoesZero.setBackgroundResource(R.drawable.bg_grey_btn)
            binding.tvShoesZero.isEnabled = false
            binding.tvShoesOne.setBackgroundResource(R.drawable.bg_grey_btn)
            binding.tvShoesOne.isEnabled = false
            binding.tvShoesTwo.setBackgroundResource(R.drawable.bg_grey_btn)
            binding.tvShoesTwo.isEnabled = false
            binding.tvShoesThree.setBackgroundResource(R.drawable.bg_grey_btn)
            binding.tvShoesThree.isEnabled = false
            binding.tvShoesFive.setBackgroundResource(R.drawable.bg_grey_btn)
            binding.tvShoesFive.isEnabled = false
            binding.tvShoesSeven.setBackgroundResource(R.drawable.bg_grey_btn)
            binding.tvShoesSeven.isEnabled = false
            binding.tvShoesTen.setBackgroundResource(R.drawable.bg_grey_btn)
            binding.tvShoesTen.isEnabled = false
            binding.btnShoesSaveCalibrate.setBackgroundResource(R.drawable.bg_grey_btn)
            binding.btnShoesSaveCalibrate.isEnabled = false
            binding.btnStartVerify.setBackgroundResource(R.drawable.bg_grey_btn)
            binding.btnStartVerify.isEnabled = false
            binding.btnShoesFailCalibrate.setBackgroundResource(R.drawable.bg_grey_btn)
            binding.btnShoesFailCalibrate.isEnabled = false
            binding.tvShoesPressWeight.text = "实测负重：0Kg"
            binding.tvShoesPressVerifyValue.text = ""
            binding.tvShoesPressVerify.text = ""
            binding.tvShoesPressAirVerifyValue.text = ""
            press.clear()
        }

    }

    private fun reSetValue() {
        runOnUiThread {
            binding.tvShoesPressZero.text = ""
            binding.tvAirPressZeroValue.text = ""
            binding.tvShoesAirPressZeroValue.text = ""
            binding.tvShoesPressOne.text = ""
            binding.tvAirPressValueOne.text = ""
            binding.tvShoesAirPressValueOne.text = ""
            binding.tvShoesPressTwo.text = ""
            binding.tvAirPressValueTwo.text = ""
            binding.tvShoesAirPressValueTwo.text = ""
            binding.tvShoesPressThree.text = ""
            binding.tvAirPressValueThree.text = ""
            binding.tvShoesAirPressValueThree.text = ""
            binding.tvShoesPressFive.text = ""
            binding.tvAirPressValueFive.text = ""
            binding.tvShoesAirPressValueFive.text = ""
            binding.tvShoesPressSeven.text = ""
            binding.tvAirPressValueSeven.text = ""
            binding.tvShoesAirPressValueSeven.text = ""
            binding.tvShoesPressTen.text = ""
            binding.tvAirPressValueTen.text = ""
            binding.tvShoesAirPressValueTen.text = ""
            binding.tvShoesZero.setBackgroundResource(R.drawable.bg_orange_btn)
            binding.tvShoesOne.setBackgroundResource(R.drawable.bg_orange_btn)
//            binding.tvShoesOne.isEnabled = false
            binding.tvShoesTwo.setBackgroundResource(R.drawable.bg_orange_btn)
//            binding.tvShoesTwo.isEnabled = false
            binding.tvShoesThree.setBackgroundResource(R.drawable.bg_orange_btn)
//            binding.tvShoesThree.isEnabled = false
            binding.tvShoesFive.setBackgroundResource(R.drawable.bg_orange_btn)
//            binding.tvShoesFive.isEnabled = false
            binding.tvShoesSeven.setBackgroundResource(R.drawable.bg_orange_btn)
//            binding.tvShoesSeven.isEnabled = false
            binding.tvShoesTen.setBackgroundResource(R.drawable.bg_orange_btn)
//            binding.tvShoesTen.isEnabled = false
            binding.btnShoesSaveCalibrate.setBackgroundResource(R.drawable.bg_grey_btn)
            binding.btnShoesSaveCalibrate.isEnabled = false
            binding.btnStartVerify.setBackgroundResource(R.drawable.bg_grey_btn)
            binding.btnStartVerify.isEnabled = false
            binding.btnShoesFailCalibrate.setBackgroundResource(R.drawable.bg_grey_btn)
            binding.btnShoesFailCalibrate.isEnabled = false
            binding.tvShoesPressWeight.text = "实测负重：0Kg"
            binding.tvShoesPressVerifyValue.text = ""
            binding.tvShoesPressVerify.text = ""
            binding.tvShoesPressAirVerifyValue.text = ""
        }
        press.clear()
    }

    private fun disConnect() {
        reSetAllPress()
        Global.address = null
        Global.connectType = -1
        foundDevices.clear()
        deviceList.clear()
        press.clear()
        adapter.submitList(emptyList())
        if (BluetoothController.macAddress != null) {
            bluetoothController.closeBuletooth(BluetoothController.macAddress)
        }
        bluetoothController.stopScanBle()
    }

    private fun reSetRissbg(riss: String) {
        binding.tvCalibRssiIdFour.setTextColor(ContextCompat.getColor(this@CalibrateActivity, R.color.black))
        binding.tvCalibRssiIdFour.setBackgroundResource(R.drawable.bg_black_frame_btn)

        binding.tvCalibRssiIdFive.setTextColor(ContextCompat.getColor(this@CalibrateActivity, R.color.black))
        binding.tvCalibRssiIdFive.setBackgroundResource(R.drawable.bg_black_frame_btn)

        binding.tvCalibRssiIdSix.setTextColor(ContextCompat.getColor(this@CalibrateActivity, R.color.black))
        binding.tvCalibRssiIdSix.setBackgroundResource(R.drawable.bg_black_frame_btn)

        binding.tvCalibRssiIdSeven.setTextColor(ContextCompat.getColor(this@CalibrateActivity, R.color.black))
        binding.tvCalibRssiIdSeven.setBackgroundResource(R.drawable.bg_black_frame_btn)

        when (riss) {
            "-40" -> {
                currentRssiThreshold = -40
            }

            "-50" -> {
                currentRssiThreshold = -50
            }

            "-60" -> {
                currentRssiThreshold = -60
            }
            "-70" -> {
                currentRssiThreshold = -70
            }
        }
//        foundDevices.clear()
//        deviceList.clear()
////        adapter.submitList(emptyList())
//        if (BluetoothController.macAddress != null){
//            foundDevices.add(connectDevice)
//        }
//        adapter.submitList(foundDevices.toList())
//        bluetoothController.startScanBle()
    }



    private lateinit var locationManager: LocationManager
    private val locationPermissionCode = 1001
    private fun checkPermission(): Boolean {
        return if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION),
                locationPermissionCode)
            false
        } else true
    }

    @SuppressLint("MissingPermission")
    private fun startNetworkLocation() {
        locationManager = getSystemService(LOCATION_SERVICE) as LocationManager
        if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            locationManager.requestLocationUpdates(
                LocationManager.NETWORK_PROVIDER,
                10000,  // 10秒更新间隔
                10f,    // 10米距离变化阈值
                locationListener
            )
        } else {
//            ToastUtils().show(this@CalibrateActivity, "请开启网络定位")
//            Toast.makeText(this, "请开启网络定位", Toast.LENGTH_SHORT).show()
        }
    }


    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == locationPermissionCode && grantResults.isNotEmpty()) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                startNetworkLocation()
            }
        }
    }

    private val locationListener: LocationListener = object : LocationListener {
        override fun onLocationChanged(location: Location) {
            val latitude: Double = location.getLatitude()
            val longitude: Double = location.getLongitude()
            val result = String.format(
                "网络定位结果:\n纬度: %.6f\n经度: %.6f",
                latitude, longitude
            )
            Global.lat = latitude
            Global.lng = longitude
            Log.e("MainActivity", "纬度: " + latitude + ", 经度: " + longitude)
        }
    }

    fun setDataToView(ShoesPressBack: ShoesPressBack) {
        val value = ShoesPressBack.value
        val press = ShoesPressBack.press
        val pressCount = ShoesPressBack.pressCount
        val airPress = ShoesPressBack.airPress
        runOnUiThread {
            binding.tvShoesPressVerify.text = ZeroClearingManage.formatWithStringFormat(press)
            binding.tvShoesPressVerifyValue.text = ZeroClearingManage.formatWithStringFormat(pressCount)
            binding.tvShoesPressAirVerifyValue.text = ZeroClearingManage.formatWithStringFormat(airPress)
            binding.tvShoesPressWeight.text = "实测负重："+ZeroClearingManage.formatWithStringFormatOne(
                value.toDouble()
            )+"Kg"

            if (this.shoesPress > 0) {
                if (value >= (shoesPress - 2) && value <= (this.shoesPress + 2)) {
                    binding.btnShoesSaveCalibrate.setEnabled(true)
                    binding.btnShoesSaveCalibrate.setBackground(resources.getDrawable(R.drawable.bg_green_btn))
                    binding.btnShoesFailCalibrate.setEnabled(false)
                    binding.btnShoesFailCalibrate.setBackground(resources.getDrawable(R.drawable.bg_grey_btn))
                } else if (value > (this.shoesPress + 2) || value < (this.shoesPress - 2)) {
                    binding.btnShoesSaveCalibrate.setEnabled(false)
                    binding.btnShoesSaveCalibrate.setBackground(resources.getDrawable(R.drawable.bg_grey_btn))
                    binding.btnShoesFailCalibrate.setEnabled(true)
                    binding.btnShoesFailCalibrate.setBackground(resources.getDrawable(R.drawable.btn_red_bg))
                }
            }

        }
    }

    fun getCalibConfig() {
        val result = parseJsonData(Global.CalibConfig)

        for(i in 0 until result.size) {
            Log.e("MainActivity", "getCalibConfigWeight: " +result.get(i).weight)
            Log.e("MainActivity", "getCalibConfigMinDifference: " +result.get(i).minDifference)
            Log.e("MainActivity", "getCalibConfigMaxDifference: " +result.get(i).maxDifference)
        }
    }

    fun checkIn(calib: Double, weight: Int): Boolean {
        var check: Boolean = true
        val result = parseJsonData(Global.CalibConfig)

        for(i in 0 until result.size) {
            Log.e("MainActivity", "getCalibConfigWeight: " +result.get(i).weight)
            Log.e("MainActivity", "getCalibConfigMinDifference: " +result.get(i).minDifference)
            Log.e("MainActivity", "getCalibConfigMaxDifference: " +result.get(i).maxDifference)
            if (weight == result.get(i).weight) {
                if (calib>=result.get(i).minDifference && calib <= result.get(i).maxDifference) {
                    check = false
                    break
                }
            }
        }
        return check
    }


    fun parseJsonData(jsonString: String): List<WeightData> {
        val weightDataList = mutableListOf<WeightData>()
        val jsonArray = JSONArray(jsonString)

        for (i in 0 until jsonArray.length()) {
            val jsonObject = jsonArray.getJSONObject(i)
            weightDataList.add(
                WeightData(
                    weight = jsonObject.getInt("weight"),
                    minDifference = jsonObject.getDouble("minDifference"),
                    maxDifference = jsonObject.getDouble("maxDifference")
                )
            )
        }
        return weightDataList
    }

    private var lastTime1: Long = 0

    fun avoidFastClick(INTERVAL: Int): Boolean {
        val curTime = System.currentTimeMillis()
        if (abs((curTime - lastTime1).toDouble()) < INTERVAL) {
            return false
        }
        lastTime1 = curTime
        return true
    }

    private fun getDate() {

        // 接收基本数据类型
        companyCode = intent.getStringExtra("companyCode").toString()
        companyName = intent.getStringExtra("companyName").toString()
        companyConfig = intent.getStringExtra("companyConfig").toString()

        wordCode = intent.getStringExtra("wordCode").toString()
        wordName = intent.getStringExtra("wordName").toString()
        shoesConfig = intent.getStringExtra("shoesConfig").toString()

        shoesCode = intent.getStringExtra("shoesCode").toString()
        shoesConfig = intent.getStringExtra("shoesConfig").toString()

        serialCode = intent.getStringExtra("serialCode").toString()
        serialName = intent.getStringExtra("serialName").toString()
        serialConfig = intent.getStringExtra("serialConfig").toString()

        colorCode = intent.getStringExtra("colorCode").toString()
        colorlName = intent.getStringExtra("colorlName").toString()
        colorConfig = intent.getStringExtra("colorConfig").toString()

        sizeCode = intent.getStringExtra("sizeCode").toString()
        sizelName = intent.getStringExtra("sizelName").toString()
        sizeConfig = intent.getStringExtra("sizeConfig").toString()

        specificationCode = intent.getStringExtra("specificationCode").toString()
        specificationName = intent.getStringExtra("specificationName").toString()
        specificationConfig = intent.getStringExtra("specificationConfig").toString()

        productSnPrefix = companyCode+shoesCode+wordCode+serialCode+specificationCode+Global.footCode+sizeCode+colorCode+Global.colorConfig

    }

    private fun calibCheck() {
        val check = ProductSnPrefixCheck("", "")
        check.mac = Global.address
        check.productSnPrefix = productSnPrefix
        val data = Gson().toJson(check)
        OkHttpUtils.postJsonAsync(
            this@CalibrateActivity,
            Api.calibCheck,
            data,
            object : DataCallBack {
                override fun requestFailure(request: Request, e: IOException) {
                    showCalibCheckDialog("检验失败，请检查网络是否异常")
                }

                @Throws(java.lang.Exception::class)
                override fun requestSuccess(result: String) {
                    val toJsonObj = JSONObject(result)
                    val code = toJsonObj.getInt("code")
                    if (code == 0) {
                        setEnableClick()
                    } else {
                        val message = toJsonObj["message"] as String
                        showCalibCheckDialog(message)
                    }
                }
            })

    }

    /**
     * 移除超时未出现的设备（蓝牙已关机）
     */
    private fun removeTimeoutDevices() {
        val currentTime = System.currentTimeMillis()
        var needUpdate = false

        // 直接遍历 foundDevices 来检查超时
        val iterator = foundDevices.iterator()
        while (iterator.hasNext()) {
            val device = iterator.next()

            // 跳过当前连接的设备
            if (device.address == BluetoothController.macAddress) {
                continue
            }

            val lastSeen = deviceTimeoutMap[device.address]

            // 如果设备超过超时时间没有出现，认为已离线
            if (lastSeen == null || currentTime - lastSeen > DEVICE_TIMEOUT) {
                iterator.remove()
                deviceTimeoutMap.remove(device.address)

                // 同时从 deviceList 中移除（如果存在）
                val deviceListIterator = deviceList.iterator()
                while (deviceListIterator.hasNext()) {
                    if (deviceListIterator.next().device.address == device.address) {
                        deviceListIterator.remove()
                        break
                    }
                }

                needUpdate = true
                Log.d(TAG, "设备离线移除: ${device.name} - ${device.address}")
            }
        }

        if (needUpdate) {
            updateDeviceListDisplay()
        }
    }

    /**
     * 更新设备列表显示
     */
    private fun updateDeviceListDisplay() {
        // 按RSSI排序
        foundDevices.sortByDescending { it.rssi }
        adapter.submitList(foundDevices.toList())
    }


}